package me.zhengjie.modules.common.rest;

import me.zhengjie.aop.log.Log;
import me.zhengjie.modules.common.domain.TAttachment;
import me.zhengjie.modules.common.service.TAttachmentService;
import me.zhengjie.modules.common.service.dto.TAttachmentQueryCriteria;
import me.zhengjie.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


/**
* @author sw
* @date 2019-08-21
*/
@RestController
@RequestMapping("api")
public class TAttachmentController {

    @Autowired
    private TAttachmentService tAttachmentService;

    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @Log("查询TAttachment")
    @GetMapping(value = "/tAttachment")
    @PreAuthorize("hasAnyRole('ADMIN','TATTACHMENT_ALL','TATTACHMENT_SELECT')")
    public ResponseEntity getTAttachments(TAttachmentQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity(tAttachmentService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @Log("新增TAttachment")
    @PostMapping(value = "/tAttachment")
    @PreAuthorize("hasAnyRole('ADMIN','TATTACHMENT_ALL','TATTACHMENT_CREATE')")
    public ResponseEntity create(@Validated @RequestBody TAttachment resources){
        return new ResponseEntity(tAttachmentService.create(resources),HttpStatus.CREATED);
    }

    @Log("新增TAttachment")
    @PostMapping(value = "/tAttachmentNew")
    @PreAuthorize("hasAnyRole('ADMIN','TATTACHMENT_ALL','TATTACHMENT_CREATE')")
    public ResponseEntity createNew(MultipartFile file, HttpServletRequest req)  throws IOException {
        String mainKey = req.getParameter("eqptcode");
//        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
//        String format2 = sdf.format(new Date());

//        String realPath = Constants.BAK_DIR;
        String realPath = uploadFolder;

        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        file.transferTo(new File(folder, newName));

        TAttachment resources = new TAttachment();
        resources.setAttatchname(newName);
        resources.setAttatchmain("资产管理");
        resources.setAttatchmainkey(mainKey);

        return new ResponseEntity(tAttachmentService.create(resources),HttpStatus.CREATED);
    }

    @Log("修改TAttachment")
    @PutMapping(value = "/tAttachment")
    @PreAuthorize("hasAnyRole('ADMIN','TATTACHMENT_ALL','TATTACHMENT_EDIT')")
    public ResponseEntity update(@Validated @RequestBody TAttachment resources){
        tAttachmentService.update(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @Log("删除TAttachment")
    @DeleteMapping(value = "/tAttachment/{id}")
    @PreAuthorize("hasAnyRole('ADMIN','TATTACHMENT_ALL','TATTACHMENT_DELETE')")
    public ResponseEntity delete(@PathVariable Integer id){
        tAttachmentService.delete(id);
        return new ResponseEntity(HttpStatus.OK);
    }

    @RequestMapping("/tAttachmentFile")
    @PreAuthorize("hasAnyRole('ADMIN','TATTACHMENT_ALL','TATTACHMENT_SELECT')")
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
//        String ipaddr = request.getParameter("ipaddr");
        String fileName = request.getParameter("fileName");// 设置文件名，根据业务需要替换成要下载的文件名
        if (fileName != null) {
            //设置文件路径
//            String realPath = Constants.BAK_DIR +Constants.fileSeperator;
            String realPath = uploadFolder +Constants.fileSeperator;

            File file = new File(realPath , fileName);
            if (file.exists()) {
                response.setContentType("application/octet-stream");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("success");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }
}